// 短消息控制器
package controllers

import (
	"encoding/json"
	"fmt"
	"github.com/boyane/chartroom/client/utils"
	"github.com/boyane/chartroom/common/message"
	"net"
)

type Sms struct {
	Conn net.Conn
	Content string
	UserId int
}

// 发送消息
func (this *Sms) SmsEmitNews() (err error) {
	var mes message.Message
	mes.Type = message.SmsGroupEmitMesType

	var data message.SmsGroupEmitMes
	data.UserId = this.UserId
	data.Content = this.Content

	bytes, err := json.Marshal(data)
	if err != nil{
		fmt.Println("SmsEmitNews -> json.Marshal fail err=", err)
		return
	}

	mes.Data = string(bytes)

	bytes, err = json.Marshal(mes)
	if err != nil{
		fmt.Println("SmsEmitNews -> json.Marshal fail err=", err)
		return
	}
	ts := utils.ClientTransfer{}
	ts.Conn = this.Conn
	err = ts.WritePkg(bytes)
	if err != nil{
		fmt.Println("SmsEmitNews -> ts.WritePkg err =", err)
		return
	}
	return
}

// 处理接收消息
func (this *Sms) handleSmsGroupEmitMes(mes string) {
	var resMes message.SmsGroupEmitResMes
	err := json.Unmarshal([]byte(mes), &resMes)

	if err != nil{
		fmt.Println("handleSmsGroupEmitMes -> json.Unmarshal fail err= ", err)
		return
	}
	info := fmt.Sprintf("接收到用户%d/t 发送的消息：%s", resMes.UserId, resMes.Content)
	fmt.Println(info)
}
